//
//  LeftViewController.swift
//  fir-mac
//
//  Created by isaced on 16/6/22.
//
//

import Cocoa
import Kingfisher
import UserNotifications
import KeychainAccess

class LeftViewController: NSViewController, UNUserNotificationCenterDelegate {
    

    @IBOutlet weak var loginBtn: NSButton!
    @IBOutlet weak var dragView: DragDestinationView!


    var apps: [FIRApp] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        dragView.delegate = self
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name.FIRSchemeUploadAction, object: nil, queue: nil) { (noti) in
            if let fileUrl = noti.object as? URL {
                self.urlschemeUploadHandle(fileUrl: fileUrl)
            }
        }
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name.FIRLoginComplete, object: nil, queue: nil) { [self] (noti) in
            self.loginSuccessHandle()
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
            if let appDelegate = NSApplication.shared.delegate as? AppDelegate {
                if appDelegate.prepareUploadUrl != nil {
                    self.urlschemeUploadHandle(fileUrl: appDelegate.prepareUploadUrl!)
                }
            }
        }
        
        //不能直接请求
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [self]
            if Keychain(service: KeychainFirmacServiceName)[KeychainFirmacAPITokenKey] != nil {
                self.loginSuccessHandle()
            }else{
                self.showLoginVC()
            }
        }
    }
    
    @IBAction func loginClick(_ sender: NSButton) {
        if sender.title == "登录" {
            showLoginVC()
        } else { //退出
            loginOutHandle()
        }
    }
    
    func showLoginVC() {
        let loginVC = self.storyboard?.instantiateController(withIdentifier: "loginVC") as! LoginVC
        self.parent?.presentAsSheet(loginVC)
    }
    
    func uploadfile(url: URL) {
        // uploading view controller
        let uploadViewController = self.storyboard?.instantiateController(withIdentifier: "UploadViewController") as! UploadViewController
        self.parent?.presentAsSheet(uploadViewController)
        uploadViewController.startParsing()
        Util.configAppInfo(appUrl: url) { (appInfo) in
            uploadViewController.stopParsing()
            if let appInfo = appInfo {
                print(appInfo)
                uploadViewController.appInfo = appInfo
                uploadViewController.startUpload()
                
                if HTTPManager.shared.isFirOrPGY == true {
                    HTTPManager.shared.firUploadApp(appInfo: appInfo,
                                                 encodingRequestSuccess: { (request) in
                                                    uploadViewController.cancelActionCallback = {
                                                        request.cancel()
                                                    }
                    }, uploadProgress: {(progress) in
                        uploadViewController.uploadingProgressIndicator.doubleValue = progress.fractionCompleted
                    }, complate: { [weak self] (success, qrCodeStr) in
                        print("upload complate")
                        uploadViewController.stopUpload()
                        uploadViewController.showResultStatus(success: success, qrCodeStr: qrCodeStr)
                        if success {
                            self?.sendNotify()
                        }
                    })
                } else {
                    HTTPManager.shared.pgyUploadApp(appInfo: appInfo,
                                                 encodingRequestSuccess: { (request) in
                                                    uploadViewController.cancelActionCallback = {
                                                        request.cancel()
                                                    }
                    }, uploadProgress: {(progress) in
                        uploadViewController.uploadingProgressIndicator.doubleValue = progress.fractionCompleted
                    }, complate: { [weak self] (success, qrCodeStr) in
                        print("upload complate")
                        uploadViewController.stopUpload()
                        uploadViewController.showResultStatus(success: success, qrCodeStr: qrCodeStr)
                        if success {
                            self?.sendNotify()
                        }
                    })
                }
                
            }else{
                print("App 解析出错...")
                uploadViewController.showResultStatus(success: false, message: "App 解析出错")
            }
        }
    }
    
    func urlschemeUploadHandle(fileUrl: URL) {
        // url && login && not uploading
        if HTTPManager.shared.APIToken != nil, !HTTPManager.shared.uploading {
            self.uploadfile(url: fileUrl)
        }
    }
    
    //没得用，奇怪
    func sendNotify() {
        let content = UNMutableNotificationContent()
        content.title = "已经上传成功"
        content.body = "快截图发给别人吧"
        content.userInfo = ["method": "new"]

        content.sound = UNNotificationSound.default
        content.categoryIdentifier = "NOTIFICATION_DEMO"

        let acceptAction = UNNotificationAction(identifier: "SHOW_ACTION", title: "显示", options: .init(rawValue: 0))
        let declineAction = UNNotificationAction(identifier: "CLOSE_ACTION", title: "关闭", options: .init(rawValue: 0))
        let testCategory = UNNotificationCategory(identifier: "NOTIFICATION_DEMO",
                                                  actions: [acceptAction, declineAction],
                                                  intentIdentifiers: [],
                                                  hiddenPreviewsBodyPlaceholder: "",
                                                  options: .customDismissAction)

        let request = UNNotificationRequest(identifier: "NOTIFICATION_DEMO_REQUEST",
                                            content: content,
                                            trigger: nil)

        // Schedule the request with the system.
        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.delegate = self
        notificationCenter.setNotificationCategories([testCategory])
        notificationCenter.add(request) { (error) in
            if error != nil {
                // Handle any errors.
            }
        }
    }
}

extension LeftViewController: DragDestinationViewDelegate {
    func callback(urlStr: String) {
        let url = URL(fileURLWithPath: urlStr)
        DispatchQueue.main.async {
            self.uploadfile(url: url)
        }
    }
}

extension LeftViewController {
    func loginSuccessHandle() {
        HTTPManager.shared.APIToken = Keychain(service: KeychainFirmacServiceName)[KeychainFirmacAPITokenKey]
        HTTPManager.shared.isFirOrPGY = Keychain(service: KeychainFirmacServiceName)[KeychainFirmacTokenType] == TokenType.fir.rawValue
        loginBtn.title = "退出" + (HTTPManager.shared.isFirOrPGY! ? "Fir" : "蒲公英")
    }
    
    func loginOutHandle() {
        try? Keychain(service: KeychainFirmacServiceName).remove(KeychainFirmacAPITokenKey)
        try? Keychain(service: KeychainFirmacServiceName).remove(KeychainFirmacTokenType)
        HTTPManager.shared.APIToken = nil
        HTTPManager.shared.isFirOrPGY = nil
        loginBtn.title = "登录"

        let alert = NSAlert()
        alert.informativeText = "退出登录成功！"
        alert.runModal()
    }
}
